package kit4j.tests.jdk.awt;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Window;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class TestWindowOpaque {

	public static void main(String[] args) throws IllegalArgumentException, SecurityException, ClassNotFoundException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		JFrame frame = createFrame("test");
		JPanel panel = createPanel(frame);

		frame.add(panel);
		
		setWindowOpaque(frame, false);

		frame.setVisible(true);
	}

	static JFrame createFrame(String title) {
		JFrame frame = new JFrame(title);

		frame.setBounds(100, 100, 400, 300);
		frame.setDefaultCloseOperation(3);
		frame.setUndecorated(true);

		return frame;
	}
	
	static void setWindowOpaque(Window window, boolean isOpaque) throws ClassNotFoundException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException {
		Class<?> awtUtilitiesClass = Class.forName("com.sun.awt.AWTUtilities");
		Method setWindowOpaqueMethod = awtUtilitiesClass.getMethod("setWindowOpaque", Window.class, Boolean.TYPE);
		
		setWindowOpaqueMethod.invoke(null, window, isOpaque);
	}

	static JPanel createPanel(final JFrame frame) {
		final ImageIcon image = createImage();

		return new JPanel() {

			private static final long serialVersionUID = 1L;

			@Override
			public void paintComponent(Graphics g) {
				if (image != null && g instanceof Graphics2D) {// 绘制背景
					Graphics2D gg = (Graphics2D) g;
					gg.drawImage(image.getImage(), 0, 0, frame.getWidth(), frame.getHeight(), frame);
				}
			}
		};
	}

	static ImageIcon createImage() {
		return new ImageIcon(ClassLoader.getSystemResource("bg.png"));
	}

}
